package org.jet.emall.security.vote;

import lombok.Setter;
import org.jet.emall.security.comp.DynamicPrivilegeManager;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;

import java.util.Collection;
import java.util.Iterator;


/**
 * @author xiaozai
 * @version 1.0
 * @date 2020-04-09 11:40
 */
public class RestfulUrlVote implements AccessDecisionVoter<FilterInvocation> {


    private final String ROLE_ANONYMOUS = "ROLE_ANONYMOUS";


    @Setter
    private DynamicPrivilegeManager dynamicPrivilegeManager;

    @Override
    public boolean supports(ConfigAttribute attribute) {

        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }

    /**
     *
     * @param authentication
     * @param object
     * @param attributes 原来的权限相关的属性，因为我们要做动态权限，对字符串形式的属性不适我们，所以这个参数没用上
     * @return
     */
    @Override
    public int vote(Authentication authentication, FilterInvocation object, Collection<ConfigAttribute> attributes) {
        //放行permitAll配置
        if( attributes!=null && !attributes.isEmpty()){
            for(ConfigAttribute attribute : attributes){
                if("permitAll".equals(attribute.toString())){
                    return ACCESS_GRANTED;
                }
            }
        }

        //取角色
        Iterator<? extends GrantedAuthority> iterator = authentication.getAuthorities().iterator();
        String role = null;
        if(iterator.hasNext()){
            role = iterator.next().getAuthority();
        }
        //如果是匿名用户，拒绝访问
        if(role==null || ROLE_ANONYMOUS.equals(role)){
            return ACCESS_DENIED;
        }

        //取url
        String requestUrl = object.getRequestUrl();
        //去掉url中的?和后边的查询串
        if(requestUrl.contains("?")){
            requestUrl = requestUrl.substring(0, requestUrl.indexOf("?"));
        }
        //取请求方法
        String method = object.getHttpRequest().getMethod();


        //调用动态权限管理器去比对权限
        return dynamicPrivilegeManager.isGrantedFor(role, requestUrl, method)? ACCESS_GRANTED:ACCESS_DENIED;

    }
}
